package com.yanftch.hdc_tools.command

import com.intellij.openapi.actionSystem.AnActionEvent
import com.yanftch.hdc_tools.common.MessageDelegate
import com.yanftch.hdc_tools.common.executeCommand
import com.yanftch.hdc_tools.common.finalCommandLine
import com.yanftch.hdc_tools.common.installAssistHap
import com.yanftch.hdc_tools.common.isCommandSucceed
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor

class CopyToPasteCommand : Command {
    override fun run(commandContext: CommandContext): Boolean {
        with(commandContext) {
            try {
                // 从剪贴板中获取内容
                val originText = getClipboardText()
//                MessageDelegate.info("PC端剪贴板内容>>$originText", action)

                // 第一步：验证是否有安装辅助 entry.hap，如果没有安装则先安装
                val executeCommand = executeCommand(finalCommandLine(hdcPath, hdc_shell_bm_dump__a))
                if (executeCommand.isBlank() || !executeCommand.contains(assist_bundleName)) {
                    // 未安装，则安装
                    MessageDelegate.info("未安装 hdc_tools 辅助APP，即将安装...", action)
                    val resultCode = installAssistHap(hdcPath) // 0 表示安装成功
                    if (resultCode == 0) {
                        realCopy(hdcPath, originText, action)
                    }
                    return false
                } else {
                    // 已安装
                    // 第二步：启动 entry.hap 的首页（就一个页面），并传递默认的参数（参数中带有要赋值给剪贴板的内容）
                    realCopy(hdcPath, originText, action)
                }
            } catch (e: Exception) {
                MessageDelegate.error("CopyToPasteCommand error: ${e.message}", action)
            }
        }
        return false
    }

    private fun realCopy(hdcPath: String, originText: String?, action: AnActionEvent) {
        if (originText.isNullOrEmpty()) {
            MessageDelegate.error("剪贴板内容为空，无法拷贝~", action)
        }
        val transformString = "'$originText'"
        val copy = executeCommand(finalCommandLine(hdcPath, start_and_copy, transformString))
        if (copy.isCommandSucceed()) {
            MessageDelegate.info("已拷贝到手机剪贴板，内容为：$transformString", action)
        } else {
            MessageDelegate.error("拷贝失败，请重试 $copy, 待拷贝内容：$transformString", action)
        }
    }

    fun getClipboardText(): String? {
        val clipboard = Toolkit.getDefaultToolkit().systemClipboard
        val contents = clipboard.getContents(null)

        return if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            contents.getTransferData(DataFlavor.stringFlavor) as String
        } else {
            null
        }
    }
}